package com.hoow.shakoow.shake

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.hoow.shakoow.R
import com.hoow.shakoow.ai.data.*
import com.hoow.shakoow.ai.enums.ProductEditEnum
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.base.BaseActivityConnectionAction
import com.hoow.shakoow.components.dialog.ImagePickerDialog
import com.hoow.shakoow.components.dialog.MessageDialog
import com.hoow.shakoow.ai.data.ReqImageUpload
import com.hoow.shakoow.databinding.ActivityUserFeedbackBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.shake.adapter.UserFeedbackImage
import com.hoow.shakoow.shake.adapter.UserFeedbackImageAdapter
import com.hoow.shakoow.shake.components.imageView.ShakeImageGallary
import com.hoow.shakoow.utils.analytics.util.AnalyticsUtil
import java.io.File


/** 用户反馈页 */
@SuppressLint("CustomSplashScreen")
class UserFeedbackActivity : BaseActivity(), BaseActivityConnectionAction {

    //布局binding
    private lateinit var mActivityBinding: ActivityUserFeedbackBinding

    // 适配器
    private lateinit var mUserFeedbackImageAdapter: UserFeedbackImageAdapter

    // 调起相机
    private var mImageIntent: Intent? = null
    private var mImageCameraActivityResultLauncher: ActivityResultLauncher<Intent>? = null
    private var mImageFilePath = ""

    // 调起相册
    private var mImageAlbumActivityResultLauncher: ActivityResultLauncher<String>? = null

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.feed_back.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivityUserFeedbackBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n", "SourceLockedOrientationActivity", "NotifyDataSetChanged")
    override fun onContentViewBinded() {
        try {
            //初始化拍照与选择图片回调
            registerTakePicActivityResultCallback()
            registerAlbumActivityResultCallback()

            // 上传图片返回
            mNetworkViewModel.onUploadFileLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        if (result.isNotBlank()) {
                            // 添加图片
                            mNetworkViewModel.mFeedbackImageList.add(
                                UserFeedbackImage(
                                    imgUrl = result,
                                    isAdd = false
                                )
                            )

                            // 刷新
                            mUserFeedbackImageAdapter.notifyDataSetChanged()
                        }
                    }
                }
            }

            // 上传相册返回
            mNetworkViewModel.onUploadUserPhotosLiveData.observe(this) {
                // 获取用户相册
                mNetworkViewModel.getUserPhotos(ReqAiBase())
            }

            // 提交反馈返回
            mNetworkViewModel.onSubmitFeedbackLiveData.observe(this) {
                if (it.isSuccess) {
                    // 清空输入
                    mActivityBinding.editFeedbackInput.text = null

                    // 清空图片列表
                    mNetworkViewModel.mFeedbackImageList.clear()
                    // 增加删除项目
                    mNetworkViewModel.mFeedbackImageList.add(
                        UserFeedbackImage(imgUrl = "", isAdd = true)
                    )

                    // 刷新
                    mUserFeedbackImageAdapter.notifyDataSetChanged()

                    Toast.makeText(
                        this@UserFeedbackActivity,
                        getText(R.string.shake_feedback_submit_success),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            // 初始化适配器
            mNetworkViewModel.mFeedbackImageList.clear()
            // 增加删除项目
            mNetworkViewModel.mFeedbackImageList.add(
                UserFeedbackImage(imgUrl = "", isAdd = true)
            )
            UserFeedbackImageAdapter.initItemSize(this)
            mUserFeedbackImageAdapter =
                UserFeedbackImageAdapter(mNetworkViewModel.mFeedbackImageList)
            mUserFeedbackImageAdapter.setItemClickListener { position, avatarLink, action ->
                if (action == UserFeedbackImageAdapter.ACTION_CLICK) {
                    //点击图片
                    val imageList = mutableListOf<UserFeedbackImage>()
                    for (index in 1 until mNetworkViewModel.mFeedbackImageList.size) {
                        val item = mNetworkViewModel.mFeedbackImageList[index]
                        imageList.add(item)
                    }

                    ShakeImageGallary.showDialogForFeedbackImages(
                        fragmentManager = supportFragmentManager,
                        dataList = imageList,
                        index = (position - 1)
                    )
                } else if (action == UserFeedbackImageAdapter.ACTION_ADD) {
                    // 去添加图片
                    // 两种，拍照与选择相册
                    ImagePickerDialog.showDialog(supportFragmentManager) { pickType ->
                        mNetworkViewModel.mImageAction = pickType
                        if (pickType == ImagePickerDialog.PICK_TYPE_ALBUM) {
                            openAblum()
                        } else if (pickType == ImagePickerDialog.PICK_TYPE_CAMER) {
                            requestExtPermissoins()
                        }
                    }
                } else if (action == UserFeedbackImageAdapter.ACTION_DELETE) {
                    // 删除选中
                    if (mNetworkViewModel.mFeedbackImageList.size > position) {
                        mNetworkViewModel.mFeedbackImageList.removeAt(position)
                        // 刷新列表
                        mUserFeedbackImageAdapter.notifyDataSetChanged()
                    }
                }
            }

            mActivityBinding.rcAblumList.layoutManager =
                StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL)
            mActivityBinding.rcAblumList.adapter = mUserFeedbackImageAdapter

            // 点击提交
            mActivityBinding.textToSubmit.setOnClickListener {
                val content = mActivityBinding.editFeedbackInput.text.toString().trim()
                if (content.isNotBlank()) {
                    // 图片列表
                    val imageUrlList = mutableListOf<String>()
                    for (item in mNetworkViewModel.mFeedbackImageList) {
                        if (!item.isAdd) {
                            if (!item.imgUrl.isNullOrBlank()) {
                                imageUrlList.add(item.imgUrl!!)
                            }
                        }
                    }
                    var imageUrls = ""
                    if (imageUrlList.isNotEmpty()) {
                        imageUrls = imageUrlList.joinToString(",")
                    }
                    // 提交
                    val reqSubmitFeedback = ReqSubmitFeedback(opinion = content, images = imageUrls)
                    mNetworkViewModel.submitFeedback(reqSubmitFeedback)
                }

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "FEEDBACK_SAVE_CLICK",
                    remark = ""
                )
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onPermissionsRequestAllPass() {
        //调起相机
        mImageCameraActivityResultLauncher?.launch(mImageIntent)
    }

    override fun takePicture() {
        //调起相机前，申请权限
        requestExtPermissoins()
    }

    override fun openAblum() {
        //调起相册
        mImageAlbumActivityResultLauncher?.launch("image/*")
    }

    /** 注册拍照回调 */
    @SuppressLint("Recycle", "Range")
    private fun registerTakePicActivityResultCallback() {
        try {
            //front
            mImageFilePath =
                getCacheImageFilePath("icfront")
            val imageFile = File(mImageFilePath)
            val imageUri: Uri = if (Build.VERSION.SDK_INT < 24) {
                Uri.fromFile(imageFile)
            } else {
                FileProvider.getUriForFile(this, "$packageName.file_provider", imageFile)
            }
            mImageIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                .apply { putExtra(MediaStore.EXTRA_OUTPUT, imageUri) }
            mImageCameraActivityResultLauncher =
                registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                    try {
                        pickResultFromCameraActivity(
                            outFilePath = mImageFilePath,
                            result = result,
                            convertFinish = { covetPath, bitmap ->
                                onHandlerImagePickResult(
                                    covetPath = covetPath,
                                    bitmap = bitmap
                                )
                            })
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 注册相册回调 */
    private fun registerAlbumActivityResultCallback() {
        try {
            mImageAlbumActivityResultLauncher =
                registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
                    try {
                        try {
                            pickResultFromAlbumActivity(
                                result = uri,
                                convertFinish = { covetPath, bitmap ->
                                    onHandlerImagePickResult(
                                        covetPath = covetPath,
                                        bitmap = bitmap
                                    )
                                })
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 处理选择/拍照回调 */
    private fun onHandlerImagePickResult(
        covetPath: String?,
        bitmap: Bitmap?
    ) {
        var validPath = false
        covetPath?.let {
            mNetworkViewModel.mImagePath = it
            validPath = true
        }

        var validBitmap = false
        bitmap?.let {
            mNetworkViewModel.mImageBitmap = it
            validBitmap = true
        }

        if (validPath and validBitmap) {
            //上传图片
            mNetworkViewModel.uploadFile(
                ReqImageUpload(
                    filePath = mNetworkViewModel.mImagePath,
                    cardType = ProductEditEnum.IMAGE_TO_IMAGE.name
                )
            )
        } else {
            MessageDialog.showDialog(
                fragmentManager = supportFragmentManager,
                message = getString(R.string.ai_please_upload_image_first),
            )
        }
    }

    /** 请求相机权限 */
    private fun requestExtPermissoins() {
        requestSpecPermissions(arrayOf(android.Manifest.permission.CAMERA))
    }
}